<template>
  <div>
    <!-- 计量及试检验设备配置策划表 -->
    <a-form-model ref="ruleForm" class="table-form" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editable ? rules : {}">
      <a-spin :spinning="loading">
        <!-- 表单 -->
        <a-card>
          <title-name title="计量及试检验设备配置策划表"></title-name>
          <a-button :disabled="!editable" type="primary" class="mb12" icon="plus" @click="handleManage"> 增加 </a-button>
    
          <a-table bordered :data-source="tableData" :columns="columns" rowKey="stringId" :scroll="{ x: 1500 }" :pagination="false">
            <template v-for="(item, index) in editableKey" :slot="item" slot-scope="text, record, index">
              <div v-if="editable" :key="item" :class="cellClass(record, item)">
                <a-select v-if="item == 'provideTheFormType'" v-model="record[item]" @change="handleChange(item, record, $event)" placeholder='请选择'>
                  <!-- (自购:0调拨:1租赁:2) -->
                  <a-select-option :value="0"> 自购 </a-select-option>
                  <a-select-option :value="1"> 调拨 </a-select-option>
                  <a-select-option :value="2"> 租赁 </a-select-option>
                </a-select>
                <a-input-number v-else-if="item == 'amount'" v-model="record[item]" @change="handleChange(item, record, $event)" :min="0" :precision="0" placeholder='请输入'/>
                <BaseInput v-else v-model="record[item]" @change="handleChange(item, record, $event)" :maxLength="item == 'remark' ? 300 :  30"/>
                <!-- <a-input v-else :class="validate && !record[item] ? 'validate_err' : ''" v-model="record[item]" @change="handleChange(item, record, $event)"  :maxLength="item == 'remark' ? 300 :  30" placeholder='请输入'/> -->
              </div>
              <template v-else>
                <span v-if="item == 'provideTheFormType'">{{['自购', '调拨', '租赁'][record.provideTheFormType]}}</span>
                <span v-else>{{record[item]}}</span>
              </template>
            </template>
            
            <template slot="action" slot-scope="text, record, index">
              <a-popconfirm v-if="editable && !record.cantdel" title="确定要删除?" @confirm="() => del(record, index)">
                <a>删除</a>
              </a-popconfirm>
            </template>
          </a-table>
        </a-card>
      </a-spin>
    </a-form-model>
    <BaseModal
      :visible="visible"
      title="增加计量及试检验设备"
      :width="800"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="modelForm"
        :model="modelform"
        :rules="modelrules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 14 }"
      >
        <a-form-model-item label="仪器/器具类型" prop="instrumentName" class="requiredFormItem">
          <a-input v-model="modelform.instrumentName" placeholder="请输入" @click="openSelect" @blur="isOpen=false"></a-input>
          <a-select style="position: absolute;left: 0;z-index: -1;" v-model="modelform.instrumentName" placeholder="请输入" show-search
            @change="isOpen=false"
            @select="isOpen=false"
            :open="isOpen"
          >
            <a-select-option v-for="(item, index) in instrumentList" :key="index" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="添加行数" prop="number" class="requiredFormItem">
          <a-input-number v-model="modelform.number" :min="1" :precision="0" />
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button @click="handleCancel">
          关闭
        </a-button>
        <a-button type="primary" @click="handleAdd">
          确认
        </a-button>
      </template>
    </BaseModal>
  </div>
</template>
<script>
import debounce from 'lodash/debounce'
import BaseModal from '@/components/BaseModal'
import BSelect from '@/components/BComponents/BSelect'
import { getList, update } from '@/api/projectManagementPlanning/meteringTestEquipmentConfiguration'
import { getGuid } from '../../projectPlanningTaskList/config.js'
export default {
  name: 'MeteringTestEquipmentConfiguration' + Date.now(),
  components: {
    BaseModal
  },
  data() {
    this.handleSearch = debounce(this.handleSearch, 800),
    this.debounce = debounce
    return {
      loading: false, // 加载控件
      validate: false,
      visible: false,
      isOpen: false,
      form: {},
      rules: {}, // 校验规则
      modelform: {
        instrumentName: undefined,
        number: undefined
      },
      modelrules: {
        instrumentName: { required: true, message: '', trigger: 'blur' },
        number: [{ required: true, message: '', trigger: 'blur' }],
      },
      instrumentList: [
        { name: '质量设备', id: '质量设备' },
        { name: '试检验设备', id: '试检验设备' }
      ],
      listData: [],
      editableKey: ['applianceName','specificationsModels','amount','provideTheFormType','remark']
    }
  },
  computed: {
    cellClass() {
      return (record, item) => {
        if (item == 'remark') return ''
        if (this.validate && (record[item] == undefined || record[item] == null || record[item] === '')) {
          return 'requiredFormItem validate_err'
        } else {
          return 'requiredFormItem'
        }
      }
    },
    tableData() {
      let list = []
      this.listData.forEach((item, index) => {
        item.detailList.forEach((sub, idx) => {
          let obj = { ...sub };
          obj.cantdel = (item.instrumentName == '质量设备' || item.instrumentName == '试检验设备') && idx === 0;
          obj.instrumentName = item.instrumentName;
          obj.stringId = sub.stringId ? sub.stringId : sub.id;
          if (idx == 0) {
            obj.rowSpan = item.detailList.length
          } else {
            obj.rowSpan = 0
          }
          obj.sort = index + 1,
          list.push(obj)
        })
      })
      return list
    },
    columns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          customRender(text, record, index) {
            const obj = {
              children: record.sort,
              attrs: {},
            };
            obj.attrs.rowSpan = record.rowSpan;
            return obj;
          }
        },
        {
          title: '仪器/器具名称',
          dataIndex: 'instrumentName',
          colSpan: 2,
          ellipsis: true,
          width: 200,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {},
            };
            obj.attrs.rowSpan = row.rowSpan;
            return obj;
          },
        },
        {
          title: '名称',
          colSpan: 0,
          dataIndex: 'applianceName',
          scopedSlots: { customRender: 'applianceName' },
        },
        {
          title: '规格型号',
          dataIndex: 'specificationsModels',
          scopedSlots: { customRender: 'specificationsModels' },
        },
        {
          title: '数量',
          dataIndex: 'amount',
          width: 160,
          scopedSlots: { customRender: 'amount' },
        },
        {
          title: '提供形式（自购、调拨、租赁）',
          dataIndex: 'provideTheFormType',
          width: 200,
          scopedSlots: { customRender: 'provideTheFormType' },
        },
        {
          title: '备注',
          dataIndex: 'remark',
          scopedSlots: { customRender: 'remark' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          scopedSlots: { customRender: 'action' }
        }
      ]
    },
    pageType() {
      return this.$route.query.pageType
    },
    editable() {
      return this.$route.query.editModel == 1
    },
    planId() {
      return this.$route.query.id
    }
  },
  mounted() {
    this.getListData()
  },
  methods: {
    getListData() {
      let param = {
        isNew: this.$route.query.version ? 1 : 0,
        planId: this.planId,
      }
      if (this.$route.query.version) {
        param.version = 'V' + this.$route.query.version
      }
      getList(param).then((res) => {
        if (res.code == 200 || res.code == 0) {
          this.listData = res.data
        }
      })
    },
    handleManage() {
      this.visible = true
    },
    handleCancel() {
      this.visible = false
      this.$refs.modelForm.resetFields()
    },
    handleAdd() {
      this.$refs.modelForm.validate(valid => {
        if (valid) {
          let hasType = this.listData.find(e => e.instrumentName == this.modelform.instrumentName);
          if (hasType) {
            this.listData = this.listData.map((item, index) => {
              if (item.instrumentName == this.modelform.instrumentName) {
                for (let i = 0; i < this.modelform.number; i++) {
                  item.detailList.push({
                    // isAdd: true,
                    amount: undefined,
                    applianceName: "",
                    stringId: getGuid(),
                    provideTheFormType: undefined,
                    remark: "",
                    specificationsModels: "",
                    version: item.version
                  })
                }
              }
              return item
            })
          } else {
            let version = this.listData.length ? this.listData[0].version : 'V1'
            let item = {
              instrumentName: this.modelform.instrumentName,
              version: version,
              detailList: []
            }
            for (let i = 0; i < this.modelform.number; i++) {
              item.detailList.push({
                // isAdd: true,
                amount: undefined,
                applianceName: "",
                stringId: getGuid(),
                provideTheFormType: undefined,
                remark: "",
                specificationsModels: "",
                version: item.version
              })
            }
            this.listData.push(item)
          }
          this.handleCancel()
        } else {
          console.log('err')
        }
      });
    },
    del(record, index) {
      this.listData = this.listData.map((item, index) => {
        if (item.instrumentName == record.instrumentName) {
          let idx = item.detailList.findIndex((v) => {
            return (v.stringId == record.stringId || v.id == record.stringId)
          })
          item.detailList.splice(idx, 1)
        }
        return item
      })
    },
    handleChange(key, record, e) {
      this.listData = this.listData.map((item, index) => {
        if (item.instrumentName == record.instrumentName) {
          let obj = item.detailList.find((v) => {
            return (v.stringId == record.stringId || v.id == record.stringId)
          })
          if (key==='provideTheFormType' || key==='amount') {
            obj[key] = e
          } else {
            obj[key] = e.target.value
          }
        }
        return item
      })
    },
    MeteringTestEquipmentConfigurationSubmit(e) {
      // this.validate = true
      let _this = this
      let flag = this.validateForm()
      if (!flag) {
        this.$warning({
          title: '温馨提示',
          content: '请将数据填写完整',
          okText: '确定'
        });
        return
      }
      this.$confirm({
        okText: '确认',
        okType: 'warning',
        cancelText: '取消',
        title: '提交?',
        content: `请确认是否要提交？`,
        onOk() {
          _this.submitForm(1)
        },
        onCancel() {
        },
      })
    },
    submitForm(type) {
      let param = {
        list: this.listData,
        planId: this.planId,
        isChange: this.pageType == 'change' ? 0 : 1, // 是变更还是编辑按钮（ 0：变更|1：编辑）
        isSubmit: type, // 按钮（ 0：保存草稿按钮|1：提交按钮）编辑使用
        version: this.listData[0].version
      }
      return update(param).then((res) => {
        if (res.code == 200 || res.code == 0) {
          let msg = type == 1 ? '提交' : '保存'
          this.$message.success(`${msg}成功！`);
          this.$close();
        }
      })
    },
    validateForm() {
      let flag = true
      if (this.listData.length == 0) {
        return false
      }
      this.listData.forEach((item, index) => {
        item.detailList.forEach((sub, idx) => {
          this.editableKey.map((e, i) => {
            if (e !== 'remark' && (sub[e] === '' || sub[e] == undefined || sub[e] == null)) {
              flag = false
            }
          })
        })
      })
      return flag
    },
    MeteringTestEquipmentConfigurationSaveDrafts(e) {
      this.submitForm(0)
    },
    openSelect() {
      // console.log(this.$refs.instrumentNameSelect)
      this.isOpen = true
    },
    handleSearch(e) {
      if (e && !this.instrumentList.find(v => v.name == e)) {
        this.instrumentList.push({id: e, name: e});
      }
    }
  }
}
</script>
<style lang="less" scoped>
 /deep/ .table-form .ant-input-number {
   width: 100%;
 }
// .ant-input {
//     border: none;
// }
// /deep/ .ant-input.validate_err {
//   background-color: #f5222d;
// }
/deep/ .requiredFormItem.validate_err .ant-input:not([disabled]),
/deep/ .requiredFormItem.validate_err .ant-time-picker-input,
/deep/ .requiredFormItem.validate_err .ant-select:not(.ant-select-disabled) .ant-select-selection,
/deep/ .requiredFormItem.validate_err .ant-calendar-picker-input,
/deep/ .requiredFormItem.validate_err .ant-input-number-input,
/deep/ .requiredFormItem.validate_err .ant-cascader-picker {
  border-color: #f5222d;
}
</style>
